const initGA = (hostname: string) => {
	const gaId = getAnalyticsConfig(hostname)?.GAId
    const script = {
		children: `
		window.dataLayer = window.dataLayer || [];
		function gtag() {dataLayer.push(arguments);}
		gtag("js", new Date());
		gtag("config", "${gaId}");`,
		type: "text/javascript",
	};
	const url = {
		src: `https://www.googletagmanager.com/gtag/js?id=${gaId}`,
		async: true,
	};
	return [url, script];
}

const initPosthog = (hostname: string) => {
    const posthogId = getAnalyticsConfig(hostname)?.posthogId
    const posthogHostname = getAnalyticsConfig(hostname)?.posthogHostname
    const script = {
		children: `(function initPosthog() {
			!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
			posthog.init('${posthogId}',{api_host:'https://${posthogHostname}', person_profiles: 'always', advanced_disable_decide: true})
			})();`,
		type: "text/javascript",
	};
	return [script];
}
// tiktok
const initTiktok = (pid: any) => {
    const script = {
		children: `!function (w, d, t) {w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie","holdConsent","revokeConsent","grantConsent"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var r="https://analytics.tiktok.com/i18n/pixel/events.js",o=n&&n.partner;ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=r,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};n=document.createElement("script")
            ;n.type="text/javascript",n.async=!0,n.src=r+"?sdkid="+e+"&lib="+t;e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(n,e)};
            ttq.load('${pid}');
            ttq.page();
            }(window, document, 'ttq');`,
		type: "text/javascript",
	};
	return [script];
}

// facebook
const initFacebook = (pid: any) => {
	const script = {
		children: `!function(f,b,e,v,n,t,s)
		{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
		n.callMethod.apply(n,arguments):n.queue.push(arguments)};
		if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
		t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');
		fbq('init', '${pid}');
		fbq('track', 'PageView');`,
		type: "text/javascript",
	};
	return [script];
}
// bigo
const initBigo = (pid: any) => {
	const script = {
		children: `window.bgdataLayer = window.bgdataLayer || [];
                function bge(){bgdataLayer.push(arguments);}
                bge('init', "${pid}");`,
		type: "text/javascript",
	};
	const url = {
		src: `https://api.affiliations.site/ad/events.js?pixel_id=${pid}`,
		async: true,
	};
	return [url, script];
};

const initGDN = (pid: any) => {
	const script = {
		children: `window.dataLayer = window.dataLayer || [];
                    if (!window.gtag) {
                        window.gtag = function() {dataLayer.push(arguments);};
                    }
                    window.gdn_config = {
                        "pid": "${pid}",
                        "eventMap": {}
                    };
                    !function(w, d, s, f, r, x) {
                        if (!document.getElementById(x)) {
                            s.type = 'text/javascript';
                            s.async = true;
                            s.src = r;
                            s.id = x;
                            f.parentNode.insertBefore(s, f);
                        }
                        gtag('js', new Date());
                        gtag('config', '${pid}');
                    }(window, document, document.createElement('script'), document.getElementsByTagName('script')[0], 'https://www.googletagmanager.com/gtag/js?id=${pid}', 'gdn_gtag_script');`,
		type: "text/javascript",
	};
	return [script];
}

// 初始化平台
const initPixel = (network: any, pid: any) => {
	let scriptArr: any[] = [];
	switch (network) {
		case "tiktok":
			scriptArr = initTiktok(pid)
			break;
		case "facebook":
			scriptArr = initFacebook(pid)
			break;
		case "bigo":
			scriptArr = initBigo(pid)
			break;
		case "GDN":
			scriptArr = initGDN(pid)
			break;
		default:
			break;
	}
	return scriptArr;
};


const initGAM = () => {
	const url = {
		src: `https://securepubads.g.doubleclick.net/tag/js/gpt.js`,
		async: true,
		crossorigin: "anonymous",
		onerror: "console.warn('GAM script failed to load')",
	};
	return [url];
}

const initAdsense = (channel: any, hostname: string) => {
	const ADSENSE_ID = getAnalyticsConfig(hostname)?.adsClientId
	const url = {
		src: `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${ADSENSE_ID}`,
		async: true,
		crossorigin: "anonymous",
		"data-ad-channel": channel,
		onerror: "console.warn('AdSense script failed to load')",
	};
    return [url];
};

// 初始化脚本GA+平台+ADS
export const loadScript = (hostname: string, queryParams: any) => {
	const javascriptArr = [
		...initGA(hostname),
		...initPosthog(hostname),
		...initPixel(queryParams.Network, queryParams.Pid),
	]
	// ...initGAM(),
	// ...initAdsense(queryParams.Channel, hostname)
	const adsEnable = getAdsEnable(hostname)
	const gamEnable = getGamEnable(hostname)
	if (adsEnable) {
		javascriptArr.push(...initAdsense(queryParams.Channel, hostname))
	}
	if (gamEnable) {
		javascriptArr.push(...initGAM())
	}
	
	// 添加错误处理脚本
	const errorHandlerScript = {
		children: `
			window.addEventListener('error', function(e) {
				if (e.target && e.target.src && e.target.src.includes('doubleclick.net')) {
					console.warn('广告脚本加载失败，可能是被广告拦截器阻止:', e.target.src);
				}
			});
		`,
		type: "text/javascript",
	};
	
	useHead({ script: [...javascriptArr, errorHandlerScript] });
}



